<!--
  @Descripttion：查询表单项共用组件
  @Author：zqy
  @Date：2020-10-16 10:20:45
  @Last Modified by：zqy
  @Last Modified time：2020-10-16 10:20:45
-->
<template>
  <div @keydown.enter="handleSearch">
    <el-form ref="refSearchContainer" 
      class="qup-search-form"
      :style="styleCss"
      :class="{'collapse':!isOpen}"
      :model="searchData" 
      size="mini" 
      :label-width="`${labelWidth}px`"
      @submit.native.prevent>
      <slot name="before" />
      <div 
        v-for="(item,index) in searchConfig" 
        :key="index" 
        class="qup-search-item" 
        :class="{'item-width-none':item.type==='checkbox' || item.type==='radio'}"
        :style="getStyle(item)"
      > 
      <!-- || (item.type==='dialog' && item.config.multiple) -->
      
        <el-form-item :label="`${item.label}：`" :prop="item.prop" :label-width="item.labelWidth || ''">
          <template v-if="item.type==='select' || (item.type==='text' && item.config && item.config.remote)">
            <el-select
              v-model="searchData[item.prop]"
              :placeholder="item.placeholder || `${!!item.config.remote?'请输入选择':'请选择'}`"
              reserve-keyword
              default-first-option 
              :filterable="item.config.filterable"
              :remote="!!item.config.remote" 
              :loading="remoteLoading"
              no-match-text="无匹配结果"
              no-data-text="无匹配结果"
              :disabled="item.disabled"
              :multiple="!!item.config.multiple"
              :remote-method="!!item.config.remote?(query)=>remoteSelections(query, item.config):undefined"
              @focus="getSelections(item.config,item)"
              @change="handleEditChange($event,item.prop)"
              clearable
              collapse-tags 
            >
              <!-- <el-option v-if="item.config.showAll" label="全部" value="-1"/> -->
              <el-option
                v-for="(option,index) in item.config.selectData"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </template>
          <template v-else-if="item.type==='dialog'">
              <!-- v-model="searchData[item.prop]" -->
            <input-with-dialog
              v-model="item.value"
              :props="{label:item.config.defaultProps.label,value:item.config.defaultProps.value}"
              :clearable="true"
              :disabled="item.disabled"
              :show-field="item.showField"
              :remote-url="item.config.remoteUrl"
              :param-field="item.config.paramField"
              :multiple="item.config.multiple"
              :focus-query="item.config.focusQuery" 
              :request-method="item.config.requestMethod"
              :option-data="(item.config && item.config.selectData) || []"
              :config="{
                title:item.dialogConfig.title,
                width:item.dialogConfig.width,
                interfacePath:item.dialogConfig.interfacePath || '',
                method:item.dialogConfig.method || 'post',
                sort:item.dialogConfig.sort || '',
                order:item.dialogConfig.order || 'desc',
                paramField:item.dialogConfig.paramField || 'paramKeyword',
                filtersRaw:item.dialogConfig.filtersRaw || [],
                paramsRaw:item.dialogConfig.paramsRaw || {},
                hidePage:item.dialogConfig.hidePage || false,
                setting:item.dialogConfig.setting || [],
                apiHeader:item.config.apiHeader || null
              }"
              @change="handleInputDlgChange($event,item.prop)"
              ></input-with-dialog>              
              <!-- -->
          </template>
          <template v-else-if="item.type==='date'">
            <div :style="itemContentStyle(item.width,item.labelWidth)">
            <el-date-picker
              v-if="!item.dateType || item.dateType ==='daterange'"
              v-model="searchData[item.prop]"
              type="daterange"
              range-separator="~"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :disabled="item.disabled"
              :start-placeholder="(item.dateConfig && item.dateConfig.startPlaceholder) || '开始日期'"
              :end-placeholder="(item.dateConfig && item.dateConfig.endPlaceholder) || '结束日期'"
              :default-time="(item.dateConfig && item.dateConfig.defaultTime) || []"
              :picker-options="(item.dateConfig && item.dateConfig.pickerOptions) || {}"
              @change="handleEditChange($event,item.prop)"
            />
             <!--  value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']" -->
            <el-date-picker
              v-else-if="item.dateType ==='date' || item.dateType ==='dates'"
              v-model="searchData[item.prop]"
              :type="item.dateType"
              :placeholder="item.placeholder || '请选择'"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :disabled="item.disabled"
              :picker-options="(item.dateConfig && item.dateConfig.pickerOptions) || {}"
              @change="handleEditChange($event,item.prop)"
            />
            <el-date-picker
              v-else-if="item.dateType ==='month' || item.dateType ==='monthrange'"
              v-model="searchData[item.prop]"
              :type="item.dateType"
              :placeholder="item.placeholder || '请选择'"
              format="yyyy-MM"
              value-format="yyyy-MM"
              :disabled="item.disabled"
              :picker-options="(item.dateConfig && item.dateConfig.pickerOptions) || {}"
              @change="handleEditChange($event,item.prop)"
            />
            <el-date-picker
              v-else-if="item.dateType ==='week'"
              v-model="searchData[item.prop]"
              type="week"
              :placeholder="item.placeholder || '请选择'"
              format="yyyy年MM周"
              value-format="yyyy年MM周"
              :disabled="item.disabled"
              :picker-options="(item.dateConfig && item.dateConfig.pickerOptions) || {}"
              @change="handleEditChange($event,item.prop)"
            />
            <el-date-picker
              v-else
              v-model="searchData[item.prop]"
              :type="item.dateType"
              range-separator="~"
              :start-placeholder="(item.dateConfig && item.dateConfig.startPlaceholder) || ''"
              :end-placeholder="(item.dateConfig && item.dateConfig.endPlaceholder) || ''"
              :placeholder="(item.dateConfig && item.dateConfig.placeholder) || '请选择'"
              :default-time="(item.dateConfig && item.dateConfig.defaultTime) || []"
              :picker-options="(item.dateConfig && item.dateConfig.pickerOptions) || {}"
              :format="(item.dateConfig && item.dateConfig.format) || ''"
              :value-format="(item.dateConfig && item.dateConfig.valueFormat) || ''"
              :disabled="item.disabled"
              @change="handleEditChange($event,item.prop)"
            />
            </div>
          </template>
          <template v-else>
            <el-checkbox-group 
              v-if="item.type==='checkbox'" 
              v-model="searchData[item.prop]"
              :disabled="item.disabled"
              @change="handleEditChange($event,item.prop)"
            >
              <el-checkbox 
                v-for="(option,index) in item.config.selectData" 
                :key="option.value" 
                :label="option.value"
              >
                {{option.label}}
              </el-checkbox>
            </el-checkbox-group>

            <el-radio-group 
              v-else-if="item.type==='radio'" 
              v-model="searchData[item.prop]"
              :disabled="item.disabled"
              @change="handleEditChange($event,item.prop)"
            >
              <el-radio
                v-for="(option,index) in item.config.selectData" 
                :key="option.value" 
                :label="option.value"
              >
                {{option.label}}
              </el-radio>
            </el-radio-group>

            <el-input 
              v-else 
              v-model="searchData[item.prop]"
              :placeholder="item.placeholder || '请输入'" 
              :disabled="item.disabled"
              clearable 
              @change="handleEditChange($event,item.prop)"
            />
          </template>
        </el-form-item>
        <div v-if="copyable  && item.type!=='checkbox' && item.type!=='radio'" 
          class="btn-copy el-icon-document-copy" 
          @click="handleCopy(item)"         
        ></div>
         <!-- v-clipboard:copy="getCopyMsg(item)" 
          v-clipboard:success="handleCopySuccess" 
          v-clipboard:error="onError" -->
      </div>
      <!-- <div class="qup-search-item">
        <el-form-item label="职务名称:" prop="positionName">
          <el-input v-model="searchData.appName" placeholder="请选择应用" @focus="visibleApp=true">
            <i slot="suffix" class="el-input__icon el-icon-search" @click.self="visibleApp=true" />
          </el-input>
        </el-form-item>
      </div> -->
      <!-- <div class="qup-search-item">
        <el-form-item label="搜索弹窗选择:" prop="categoryTypeId">
          <el-select
            v-model="searchData.categoryTypeId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入搜索消息类型"
            :remote-method="remoteMsgType"
            :loading="typeLoading"
            @change="handleChangeType"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
          <i class="qup-select-input-search el-input__icon el-icon-search" @click.self="typeVisible=true" />
        </el-form-item>
      </div> -->
      <slot/>
      <div class="qup-search-item search-btns"
        :class="{'btns-line-break':showBtnLineBreak}">
        <el-button v-if="!hideMoreBtn" type="text" size="mini" class="btn-more" @click="toggleMore">
          <template v-if="isOpen">
            <span>收起</span><i class="el-icon-arrow-up" />
          </template>
          <template v-else>
            <span>更多</span><i class="el-icon-arrow-down" />
          </template>
        </el-button>
        <el-button size="mini" @click="handleClear" class="btn-custom">
          <svg-icon icon-class="shanchulajixiang-line" /> 清空
        </el-button>
        <el-button size="mini" type="primary" @click="handleSearch" class="btn-custom">
          <svg-icon icon-class="sousuo-line" /> 搜索
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
/**
 * 配置信息（数组）
 * searchConfig :
 *  type: 类型 （text 文本输入框，select 下拉选择 ， date 日期选择 ， checkbox 复选框 ，radio 单选框 , dialog 带弹窗的输入框 ）
 *  dateType：日期类型配置
 *  prop：入参的字段名
 *  label：标签文本
 *  value：绑定默认值
 *  placeholder：空值时的提示文字
 *  filter：是否为filter参数类型,默认true （true/false,true对应filtersRaw，false对应paramsRaw）
 *  config: 选项配置参数
 * 
*/
/**
 * searchConfig > config 选项配置说明
* remote：是否远程搜索
* requestMethod：远程搜索请求方式（post ,get ;默认为get）
* dataUrl: 获取焦点时请求接口地址(TODO:暂时废弃，暂仅select远程时可用)
* remoteUrl： 远程搜索请求接口地址
* paramField：远程搜索参数名
* defaultProps:字段配置选项 默认值为{label:'label',value:'value'},
* selectData:选项集合
* multiple:是否多选(true/false,默认false),
* filterable：是否可搜索
* paramsRaw：额外查询参数
* excludes:排除值
 *  */
/**
 * searchConfig > dailogConfig 弹窗配置说明
 *  title:弹窗标题
 *  interfacePath:弹窗分页查询接口地址
 *  setting：弹窗表格配置(如：[{prop:'typeCode',title:'类型编码'},{prop:'typeName',title:'消息类型'}])
*/

import {getRemoteData} from "./apis";
export default {
  name: 'SearchForm',
  props: {
    searchConfig:{
      type:Array,
      required: true,
      default:()=>[]
    },//搜索项配置
    labelWidth:{
      type:[String,Number],
      default:100
    },// 标签宽度
    copyable:{
      type:Boolean,
      default:true
    },
    defaultRow:{
      type:Number,
      default:1
    } // 默认行数
  },
  data() {
    return {
      isOpen: false, // 是否展开所有搜素条件
      searchData:{},
      remoteLoading: false, // 远程搜索加载
      remoteSelectEventData: {}, // 搜索项编辑下拉远程配置
      hideMoreBtn:true,//是否隐藏更多按钮
      containrWidth:0,// 搜索容器的宽度
      itemList:[],// 搜索项的宽度
      rowList:[], // 搜索行的宽度
      btnsWidth:126 //操作框的宽度(初始值为移除“更多”按钮以后的宽度)
    }
  },
  computed: {
    // 收起状态时，搜索容器是否设置右间距
    showPaddingRight(){
      if(this.isOpen || this.rowList.length===0) return false
       // 获取第一行的搜索项宽度
      const firstWidth = this.rowList[0].width || 0
      // 判断第一行是否能显示完整
      return firstWidth > this.containrWidth - this.btnsWidth + 20 // 20 为每一行最后一项的右填充间距
    },
    // 展开状态时，操作项是否换行显示
    showBtnLineBreak(){
      // 判断最后一行
      if(!this.isOpen || this.rowList.length===0) return false
      // 获取最后一行的搜索项总宽度
      const lastWidth = this.rowList[this.rowList.length-1].width || 0
      // console.log('最后一行的宽度',lastWidth,this.containrWidth,this.btnsWidth)
      // 判断最后一行是否能显示完整
      return lastWidth > this.containrWidth - this.btnsWidth + 20 // 20 为每一行最后一项的右填充间距
    },
    styleCss(){
      const styl ={
        paddingRight:this.showPaddingRight?`${this.btnsWidth}px`:'0px'
      }
      if(!this.isOpen){
        styl.height=`${this.defaultRow * 39}px`
      }
      return styl
    }
  },
 created(){
   this.initSearchOption(true)
  },
  mounted(){
    this.$nextTick(()=>{
      this.initLayOutData()
      setTimeout(()=>{
        this.initLayOutData()
      },500)
    })
    window.onresize = () => {
      return (() => {
        this.initLayOutData()
      })()
    }
  },
  watch:{
    searchConfig:{
      handler(val,oldVal){
       this.initSearchOption()
      },
      deep:true
    },
    searchData:{
      handler(val,oldVal){
        this.$emit('data-change',val)
      },
      deep:true
    }
  },
  methods: {
    // 初始化搜索项
    initSearchOption(flag=false){
      const reqType=['select','checkbox','radio']
      const promiseList = []
      this.searchConfig.forEach((v,index)=>{
        v.type = v.type.toLocaleLowerCase()
        v.filter = v.filter !== false
        let value = v.value
        if(v.value=== undefined || v.value === null){
          value =''
        }
        value = typeof value==='number' ? value : value || ''
        if((v.type==='checkbox' || 
          (v.type==='select' && v.config.multiple) || 
          (v.type==='dialog' && v.config.multiple)) &&
          (!value || typeof value==='string') ){
            value = []
        }
        
        if(flag){
          this.$set(this.searchData,v.prop,value)
        }
        if((reqType.includes(v.type)) 
          && v.config
          && (!v.config.selectData || v.config.selectData.length===0)  
          && v.config.remoteUrl 
          && !(v.config.lastApi && v.config.remoteUrl===v.config.lastApi)
        ){
          promiseList.push(this.getAsyncOptions(v.config))
        }
      })

      if(promiseList.length===0) return
      Promise.all(promiseList).then((results) => {
        results.forEach(v=>{
          if(v.ev && v.selectData && v.lastApi){
            this.$set(v.ev,'selectData',v.selectData)
            this.$set(v.ev,'lastApi',v.lastApi)
          }
        })
      }).catch((err) => {
        
      })
    },
    // 初始化搜索项布局宽度
    initLayOutData(){
      if(!this.$refs.refSearchContainer) return
      const el = this.$refs.refSearchContainer.$el
      if(!el) return
      const containrWidth = el.clientWidth // 搜索容器的总宽度
      const containrHeight = el.clientHeight
      const itemEls = el.getElementsByClassName('qup-search-item')
      const length = itemEls.length // 搜索项个数
      const lastIndex = length-2 // 最后一个搜索项的序号
      const tmpRows = [] // 记录每一行搜索数据
      const itemList=[] // 记录每一项的宽度数据
      let rowWidth = 0 // 搜索项每一行的宽度
      // console.log(itemEls)
      // 遍历搜索项获取每一项的宽度
      for(const i in itemEls ){
        const item = itemEls[i]
        const width = item.clientWidth // 当前搜索项宽度
        if(i < length-1){
          //计算 除操作项以外的所有搜索项
          itemList.push(width)
          rowWidth += width
          if(rowWidth > containrWidth){
            // 当行宽大于容器宽度时,换行且存储上一行的宽度与序号
            tmpRows.push({
              width : rowWidth - width, // 上一行宽度
              last :  i-1 // 上一行末项序号
            })
            rowWidth = width // 当前行的初始宽度

            if(i == lastIndex){
              // 最后一行
              tmpRows.push({
                width : rowWidth, // 当前行宽度
                last :  i // 当前行末项序号
              })
            }

          }else{
            if(i == lastIndex){
              // 最后一行
              tmpRows.push({
                width : rowWidth, // 当前行宽度
                last :  i-1 // 当前行末项序号
              })
            }
          }
        }
        /* if(i == length -1){
          // 记录操作区域的宽度
          optLeft = item.offsetLeft
          btnsWidth = item.clientWidth
        } */
      }
      let excludeMoreWidth = 126  // 不包含更多按钮的操作层宽度

      if(tmpRows.length <= 1 &&  rowWidth <= containrWidth - excludeMoreWidth){
        //当搜索项宽度大于容器宽度时，展示“更多”按钮
        this.hideMoreBtn = true
      }else{
        this.hideMoreBtn = false
      }
      
      this.containrWidth = containrWidth
      this.rowList = tmpRows
      // 搜索操作按钮框的宽度(带“更多”按钮 194px ，无更多按钮 126px)
      this.btnsWidth = this.hideMoreBtn ? 126 : 194

    },
    // 文本框值改变
    handleEditChange(data,feild) {
      this.$emit("edit-change", {prop:feild,value:data})
    },
    // 展开/关闭搜索条件
    toggleMore() {
      this.isOpen = !this.isOpen
      this.$emit('visible-change',this.isOpen) 
    },
    // 清空表单
    handleClear(){
      this.$refs['refSearchContainer'].resetFields()
      this.searchConfig.forEach(item=>{
        if(item.type==='dialog'){
          // item.value=[]
          this.$set(item,'value',[])
          // this.$set(this.searchData,item.prop,'')
          // return
        }
        const valueType = typeof this.searchData[item.prop]
        const newVal = (valueType==='string' || typeof value==='number' || valueType ==='undefined')?'':[]
        this.$set(this.searchData,item.prop,newVal)
      })
      const params=this.getQueryParams()
      this.$emit("clear",params)
    },
    // 搜索  
    handleSearch(){
      const params=this.getQueryParams()
      this.$emit('search',params)
    },
    // 获取组合查询参数
    getQueryParams(){
      const filtersRaw=[]
      const paramsRaw={}
      this.searchConfig.forEach((item,index)=>{
        let value=this.searchData[item.prop]
        if(Array.isArray(value)){
          // 去数组空值
          value =value.filter(v=>{
            if(typeof v ==='number'){
              v = `${v}`.trim()
            }else if(typeof v==='string'){
              v = v.trim()
            }
            return (v!==null && v!==undefined && v!=='')
          })
        }
        else if(typeof value ==='number'){
          value = `${value}`
        }
        if(value && value.length){
          if(typeof value==='string'){
            value=value.trim()
          }
          if(!item.filter){
            if(item.type==='date'){
              if(value && Array.isArray(value)){
                if(value.length===2){
                  value=[`${value[0]}`,`${value[1]}`]
                }else{
                  const newVal=value.map(v=>{
                    return `${v}`
                  })
                  value=newVal
                }
              }
              // value = value.join(',')
            }
            paramsRaw[item.prop] = value
          }else{
            if(item.type==='date'){
              if(item.dateType && (item.dateType!=='daterange' && item.dateType!=='datetimerange')){
                let operator = item.operator || '='
                if(Array.isArray(value)){
                  operator = item.operator || 'in'
                  value=`[${value.join(',')}]`
                }
                 filtersRaw.push({
                  id:`${item.prop}`,
                  property:item.prop,
                  operator,
                  value
                })
              }else{
                if(Array.isArray(value) && value.length===2){
                  // 日期范围
                  filtersRaw.push({
                    id:`${item.prop}0`,
                    property:item.prop,
                    operator:'>=',
                    value:`${value[0]} 00:00:00`
                  })
                  filtersRaw.push({
                    id:`${item.prop}1`,
                    property:item.prop,
                    operator:'<=',
                    value:`${value[1]} 23:59:59`
                  })
                }
              }
            } else {
              let operator= item.operator || (item.type==='text'?'like':'=')
              if(item.type==='text' || item.type==='dialog'){
                if(!item.single){
                  value=value.replaceAll('\\s{1,}', ',')
                  value=value.replace(/\s/g,",").replace(/\n/g,",")
                  let valArr=value.split(',')
                  if(valArr.length>1){
                    operator = item.operator || 'in'
                    // value=`['${value.replace(/,/g,"',")}']`
                    value=`[${valArr.join(',')}]`
                  }
                }
              }else if(item.type==='select' || item.type==='checkbox'){
                if(Array.isArray(value)){
                  operator =item.operator || 'in'
                  // value=`['${value.join(',').replace(/,/g,"',")}']`
                  value=`[${value.join(',')}]`
                }
              }
              filtersRaw.push({
                id:item.prop,
                property:item.prop,
                operator,
                value
              })

            } 
          }
        }
      })
      return { filtersRaw,paramsRaw }
    },
    // 获取初始选项值
    getAsyncOptions(ev) {
      return new Promise(async(resolve, reject) => {
        if(!ev || (ev.filterable && ev.focusQuery===false)) {
          reject()
          return
        }
        // this.remoteSelectEventData = ev
        if(ev.remoteUrl && ev.remoteUrl !== '' &&  (!ev.selectData || ev.selectData.length===0)) {
          // let params={[ev.paramField || 'paramKeyword']:''}
          let params={}
          if(ev.paramsRaw){
            params={...params,...ev.paramsRaw}
          }
          if(ev.paramsType===1 ){
            // formData方式
            const formObj = new FormData()
            formObj.append('page', 1)
            formObj.append('rows', 50)
            formObj.append('filtersRaw', JSON.stringify(ev.filtersRaw || []))
            formObj.append('paramsRaw', JSON.stringify(params))
            params = formObj
          }
          const apiHeader = ev.apiHeader || null
          let selectData = []
          await getRemoteData(ev.requestMethod,ev.remoteUrl,params,apiHeader).then(res => {
            const resData = res.data ? (res.data.records || res.data) : []
            selectData = this.getAbleList(ev,resData)
          }).catch(()=>{})
          // this.$set(ev,'selectData',dataList)
          // this.$set(ev,'lastApi',ev.remoteUrl)
          resolve({
            ev,
            selectData,
            lastApi:ev.remoteUrl
          })
        }else{
          reject()
        }
      })
    },
    /**
     * 初始化选项值
     * @param {String} prop 筛选项字段名
     * @param {Object} config 配置数据对象
    */
    async initSelectData(prop,config){
      const index = this.searchConfig.findIndex(v => v.prop === prop)
      if(index==-1) return
      const reqType=['select','checkbox','radio']
      if(!reqType.includes(this.searchConfig[index].type)) return
      const newConfig = {...this.searchConfig[index].config,...config}
      if(config.remoteUrl){
        newConfig.selectData = []
        await this.getAsyncOptions(newConfig).then(res=>{
          if(res.lastApi && res.selectData){
            newConfig.lastApi = res.lastApi
            newConfig.selectData = res.selectData
          }
        })
      }
      this.$set(this.searchConfig[index],'config',newConfig)
      const value = this.searchData[prop]
      if(!value || value.length == 0) return
      if(value instanceof Array ){
        const flag = value.every(val=>{
          return newConfig.selectData.some(n=>`${n.value}` === `${val}`)
        })
        if(!flag){
          this.$set(this.searchData,prop,[])
        }
      }else{
        const flag = newConfig.selectData.some(v=> `${v.value}` === `${value}`)
        if(!flag){
          this.$set(this.searchData,prop,'')
        }
      }
    },
    // 获取初始选项值
   getSelections(ev) {
      if (ev) {
        if(ev.filterable && ev.focusQuery===false) return
        // this.remoteSelectEventData = ev
        if(ev.remoteUrl && ev.remoteUrl !== '' &&  (!ev.selectData || ev.selectData.length===0)) {
          // let params={[ev.paramField || 'paramKeyword']:''}
          let params={}
          if(ev.paramsRaw){
            params={...params,...ev.paramsRaw}
          }          
          if(ev.paramsType===1 ){
            // formData方式
            const formObj = new FormData()
            formObj.append('page', 1)
            formObj.append('rows', 50)
            formObj.append('filtersRaw', JSON.stringify(ev.filtersRaw || []))
            formObj.append('paramsRaw', JSON.stringify(params))
            params = formObj
          }
          const apiHeader = ev.apiHeader || null
          getRemoteData(ev.requestMethod,ev.remoteUrl,params,apiHeader).then(res => {
            const resData = res.data ? (res.data.records || res.data) : []
            const dataList = this.getAbleList(ev,resData)
            this.$set(ev,'selectData',dataList)
            this.$set(ev,'lastApi',ev.remoteUrl)
          })
        }
      }
    },
    // 远程搜索
    remoteSelections(keyword,data) {
      if (keyword.trim() == '') return
      const rqUrl = data.remoteUrl
      const rqMethod = data.requestMethod ? data.requestMethod : 'get'
      this.remoteLoading = true
      // let params = {[data.paramField || 'paramKeyword']:keyword}
      let params = {}
      if(data.paramsRaw){
        params={...params,...data.paramsRaw}
      }
      if(keyword && keyword.length){
        params[data.paramField || 'paramKeyword']= keyword
      }
      if(data.paramsType===1 ){
        // formData方式
        const filtersRaw = data.filtersRaw || []
        if(data.customName){
          const tmpRaw = {
            id: Math.floor(Math.random() * 0xffffffffff).toString(16),
            value: val,
            property: data.customName,
            operator: 'like'
          }
          const index  = filtersRaw.findIndex(v=>v.property===data.customName)
          if(index>-1){
            this.$set(filtersRaw,index,tmpRaw)
          }else{
            filtersRaw.push(tmpRaw)
          }
          delete params[data.paramField || 'paramKeyword']
        }        
        const formObj = new FormData()
        formObj.append('page', 1)
        formObj.append('rows', 50)
        formObj.append('filtersRaw', JSON.stringify(filtersRaw))
        formObj.append('paramsRaw', JSON.stringify(params))
        
        params = formObj
      }

      const apiHeader = data.apiHeader || null
      getRemoteData(rqMethod,rqUrl,params,apiHeader).then(res => {
        const resData = res.data ? (res.data.records || res.data) : [] 
        const dataList = this.getAbleList(data,resData)
        data.selectData = dataList
        this.remoteLoading = false
      }).catch(()=>{
        this.remoteLoading = false
        data.selectData = []
      })
    },
    // 监听输入框值的变化
    handleInputDlgChange(data,fieldName){
      let value=[]
      if(data && Array.isArray(data)){
        value=data.map(v=>{
          return v.value
        })
      }
      this.$set(this.searchData,fieldName,value.join(','))
      this.$nextTick(()=>{
        this.$emit("edit-change", {prop:fieldName,value:data})
      })
    },
    // 复制数据处理
    handleCopy(item){
      let msg=this.searchData[item.prop]
      if(item.type==='dialog'){
        msg = ''
        if(item.value && item.value.length){
          const msgArr=item.value.map(v=>{
            return v.label
          })
          msg=msgArr.join(',')
        }
      }else if(item.type==='select'){
        msg=''
        if(item.config && item.config.selectData){
          const selectVal=this.searchData[item.prop]
          let msgArr=[]
          item.config.selectData.forEach(v=>{
            if(item.config.multiple){
              if(selectVal.includes(`${v.value}`)){
                msgArr.push(v.label)
              }
            }else{
              if(`${selectVal}`===`${v.value}`){
                msgArr=[`${v.label}`]
              }
            }
          })
          msg=msgArr.join(',')
        }
      }
      
      this.$copyText && this.$copyText(msg).then((e)=>{
        this.$message.success('复制成功')
      },(e)=> {
        console.log('Can not copy',e)
      })
    },
    // 获取搜索项的样式
    getStyle(item){
      const styleObj = {}
      if(item.width){
        styleObj.width=item.width
      }
      return styleObj
    },
    // 更新搜索项的值
    updateValue(prop,val){
      this.$set(this.searchData,prop,val)
    },
    itemContentStyle(width,labelWidth){
      const styleObj = {width:'200px'}
      let lableW = labelWidth || this.labelWidth
      if(width && lableW){
        if(!isNaN(lableW)){
          lableW=`${lableW}px`
        }
        styleObj.width = `calc(${width} - ${lableW})`
      }
      return styleObj
    },
    getAbleList(ev,data){
      let p = ev.defaultProps ? ev.defaultProps : { label: 'label', value: 'value' }
      const excludes = ev.excludes || [] 
      let d = []
      if (excludes instanceof Array && excludes.length > 0) {
        d = data.filter(e => !excludes.includes(e[p.value]))
      }else{
        d = data
      }
      const resList = d.map(item => {
        return { value: item[p.value], label: item[p.label] }
      })
      return resList
    },
  }
}
</script>
<style lang='scss' scoped>
@import "../../../theme/qup-theme";

.btn-custom{
  padding:  0 10px !important;
  .svg-icon{
    margin-right: 5px;
  }
}
</style>
